package com.ygqh.baby.controller.admin;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ygqh.baby.ao.DataStatus;
import com.ygqh.baby.ao.FileType;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.Message.Type;
import com.ygqh.baby.ao.PublishStatus;
import com.ygqh.baby.ao.PurchaseStatus;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.ao.ResultSet;
import com.ygqh.baby.po.YgPages;
import com.ygqh.baby.service.FileService;
import com.ygqh.baby.service.FreemarkerService;
import com.ygqh.baby.service.WxMpAuthorityService;
import com.ygqh.baby.service.YgPagesService;
import com.ygqh.baby.utils.HttpUtil;
import com.ygqh.baby.utils.JsonUtils;

@Controller
@RequestMapping("/admin/pages")
public class PagesController extends BaseController<Object, java.lang.Long> {
	@Autowired
	private YgPagesService ygPagesService;
	@Autowired
	private FreemarkerService freemarkerService;
	@Autowired
	private FileService fileService;
	@Autowired
	private WxMpAuthorityService wxMpAuthorityService;
    @Value("${image.upload.temp.url}")
    private String tempUrl;  
    @Value("${oss.aliyun.endpoint}")
    private String endpoint;
    @Value("${oss.aliyun.templatebucketName}")
    private String templatebucketName;
    @Value("${template.filename}")
    private String templateFileName;
    
    
   
    
	@RequestMapping("searchPages")
	@ResponseBody
	public Map<String, Object> searchPages(String q, QueryInfo queryInfo) {
		ResultSet<YgPages> resultSet = ygPagesService.search(queryInfo, q);
		return resultSet.toDatatables(null);
	}

	@RequestMapping("savePages")
	@ResponseBody
	public Message savePages(String page) {
		YgPages ygimg = JsonUtils.toObject(page, YgPages.class);
		if(ygimg.getId()!=null){
		ygimg.setUpdateBy(getSession().getTrueName());
		ygimg.setUpdateTime(new Date());
		ygPagesService.update(ygimg);		
		}else{
			ygimg.setCreateBy(getSession().getTrueName());
			ygimg.setCreateTime(new Date());
			ygimg.setUpdateBy(null);
			ygimg.setUpdateTime(null);
			ygimg.setPublishStatus(PublishStatus.NoPublish);
			ygPagesService.saveAndReturnId(ygimg);		
		}
		return Message.success(ygimg.getId());
		

	}
	@RequestMapping("updatePageStatus")
	@ResponseBody
	public Message updatePageStatus(Long id) {
		YgPages ygPages =new YgPages();
		ygPages.setId(id);
		ygPages.setUpdateBy(getSession().getTrueName());
		ygPages.setUpdateTime(new Date());
		ygPages.setStatus(DataStatus.Delete);
		
		return ygPagesService.update(ygPages) == 1 ? SUCCESS_MESSAGE : ERROR_MESSAGE;

	}

	@RequestMapping("getPagesById")
	@ResponseBody
	public YgPages getPagesById(Long id) {		
		return ygPagesService.findById(id);
	}
	
	@RequestMapping("updatePublishStatus")
	@ResponseBody
	public Message updatePublishStatus(Long id) {
		YgPages ygPages =new YgPages();
		ygPages.setId(id);
		ygPages.setPublishStatus(PublishStatus.Published);
		ygPages.setUpdateBy(getSession().getTrueName());
		ygPages.setUpdateTime(new Date());
		ygPagesService.update(ygPages);
		return SUCCESS_MESSAGE;
	}
	@RequestMapping("review")
	@ResponseBody
	public Message review(Long id,HttpServletRequest request) throws IOException {				
		return reviewPage(id,request);
	}
	@RequestMapping("publishPage")
	@ResponseBody
	public Message publishPage(Long id,String pageLink,HttpServletRequest request) throws IOException {
		//判断是否已经预览了 
		int i=pageLink.lastIndexOf('/');	
		String fileName=pageLink.substring(i+1);
		
		String url=endpoint.replace("oss", templatebucketName+".oss")+"/review/"+fileName;
		String result=HttpUtil.get(url);
		if(result==null||result.contains("NoSuchKey")){//先预览
			return reviewPage(id,request);
			 
			
		}else{
			fileService.uploadTemplateHtml2Target("review/"+fileName,fileName);	
			//上传小程序页面
			String smallFile=fileName.replace(".html", "_small.html");
			fileService.uploadTemplateHtml2Target("review/"+smallFile,smallFile);	
		    url=wxMpAuthorityService.getQrCodeUrl(pageLink, request, FileType.QrCode);
		    //更新状态
		    YgPages ygPages=new YgPages();
		    ygPages.setId(id);
		    ygPages.setPublishStatus(PublishStatus.Published);
		    ygPages.setUpdateBy(getSession().getTrueName());
		    ygPages.setUpdateTime(new Date());
		    ygPagesService.update(ygPages);
		  return Message.success("发布",url);
		  
		}
			
	  
		
		
	}
	
	private Message reviewPage(Long id,HttpServletRequest request) throws IOException{
		YgPages ygPage=ygPagesService.findById(id);
		Map<String,Object> data=new HashMap<String, Object>();
		
		data.put("ygPages", ygPage);
		data.put("shareTitle", ygPage.getPageTitle());
		data.put("version",new Date().getTime()+"");
		
		//判断最后一下/
		int i=ygPage.getPageLink().lastIndexOf('/');		
		String filename=ygPage.getPageLink().substring(i+1);
		//生成html
		String msg=freemarkerService.crateHTML(templateFileName,filename, data);
		if(msg!="")return new Message(Type.error,msg);
		//获取html 上传到oss	
		fileService.uploadHtml2Oss("review/"+filename, tempUrl+"/"+filename);
		//生成 二维码
	    String url=wxMpAuthorityService.getQrCodeUrl(ygPage.getPageLink().replace("/static", "/static/review"), request, FileType.QrCode);
	    
	    //生成小程序页面
	    ygPage.setPageLink(ygPage.getPageLink().replace("http:","https:"));
	    ygPage.setShareImage(ygPage.getShareImage().replace("http://img.yiigoo.com", "https://static.yiigoo.com"));
	    ygPage.setPageContent(ygPage.getPageContent().replaceAll("http://img.yiigoo.com", "https://static.yiigoo.com"));
	    data.put("ygPages", ygPage);
		data.put("shareTitle", ygPage.getPageTitle());
		data.put("version",new Date().getTime()+"");
		
		//判断最后一下/
		 i=ygPage.getPageLink().lastIndexOf('/');		
		 filename=ygPage.getPageLink().substring(i+1).replace(".", "_small.");
		//生成html
		 msg=freemarkerService.crateHTML(templateFileName.replace("action", "action-small"),filename, data);
		if(msg!="")return new Message(Type.error,msg);
		//获取html 上传到oss	
		fileService.uploadHtml2Oss("review/"+filename, tempUrl+"/"+filename);
		//生成 二维码
	    
	    return Message.success("预览",url);
	    
	}
	
	
	
	

	
}
